package com.heima.search.config;

import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.thread.ApThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义的springmvc拦截器
 */
public class WebMvcInterceptor implements HandlerInterceptor {
    /**
     * 目的方法执行之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取token
        String token = request.getHeader("token");
        //2.解析token
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        Integer userId = (Integer) claimsBody.get("id");

        //3.封装到threadLocal中
        ApUser apUser=new ApUser();
        apUser.setId(userId);
        ApThreadLocal.setApUser(apUser);

        //4、放行
        return true;
    }

    /**
     * 目的方法执行之后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ApThreadLocal.removeApUser();
    }
}